﻿using System;
using System.Windows.Forms;
using System.Collections;
using System.Diagnostics;
using System.Xml;
using System.IO;

namespace DataUpload
{
    public partial class FrmBaseFormat : Form
    {
        private MainForm _container = null;
        internal SortedList ucBaseFormat;
        internal FrmCultureInfo frmCultureInfo;

        public FrmBaseFormat()
        {
            InitializeComponent();
        }

        public FrmBaseFormat(MainForm container)
        {
            _container = container;
            InitializeComponent();
            lstFiles.SmallImageList = _container.imgList;
            ucBaseFormat = new SortedList();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (lstFiles.Items.Count != ucBaseFormat.Count)
            {
                string missItems = "";
                foreach (ListViewItem item in lstFiles.Items)
                {
                    if (!ucBaseFormat.ContainsKey(item.Tag.ToString()))
                        missItems += item.Text + "; ";
                }
                missItems = missItems.Remove(missItems.Length - 2);
                MessageBox.Show("Did you miss something: " + missItems);
                return;
            }

            for (int i = 0; i < lstFiles.Items.Count; i++)
            {
                bool status = ((UCBaseFormat)ucBaseFormat.GetByIndex(i)).IsValid;
                if (!status)
                {
                    lstFiles.Items[i].Selected = true;
                    lstFiles_SelectedIndexChanged(sender, e);
                    MessageBox.Show("Do you miss something?");
                    return;
                }
            }

            this.Hide();
            if (_container.frmMapping == null)
                _container.frmMapping = new FrmMapping(_container);
            _container.frmMapping.Show();
            _container.frmMapping.Focus();
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            this.Hide();
            _container.frmAddFiles.Show();
            _container.frmAddFiles.Focus();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            _container.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (lstFiles.Items.Count == 0 || lstFiles.SelectedItems.Count == 0)
                return;

            string selectingPath = lstFiles.SelectedItems[0].Tag.ToString();

            XmlDocument newXml = new XmlDocument();
            UCBaseFormat ucFormat = (UCBaseFormat)ucBaseFormat[selectingPath];

            if (ucFormat.txtColSep.Text == ""
                || ucFormat.txtRowSep.Text == ""
                || ucFormat.txtQuote.Text == ""
                || ucFormat.txtDecimal.Text == ""
                || ucFormat.txtDigit.Text == ""
                || ucFormat.txtDateFormat.Text == ""
                || ucFormat.txtTimeFormat.Text == ""
                || ucFormat.cboCulture.Text == "")
            {
                MessageBox.Show("Some formats have not been filled!");
                return;
            }

            newXml.CreateXmlDeclaration("1.0", "UTF-8", String.Empty);
            string innerXml = "<file>" + selectingPath + "</file>";
            innerXml += "<lastmoddate>" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + "</lastmoddate>";

            innerXml += "<fieldsep>" + ucFormat.txtColSep.Text + "</fieldsep>";
            innerXml += "<recordsep>" + ucFormat.txtRowSep.Text + "</recordsep>";
            innerXml += "<quotationmark>" + ucFormat.txtQuote.Text + "</quotationmark>";
            innerXml += "<hasexplicittable>" + ucFormat.ckcHasExplicitTable.Checked.ToString() + "</hasexplicittable>";
            innerXml += "<decimal>" + ucFormat.txtDecimal.Text + "</decimal>";
            innerXml += "<digit>" + ucFormat.txtDigit.Text + "</digit>";
            innerXml += "<dateformat>" + ucFormat.txtDateFormat.Text + "</dateformat>";
            innerXml += "<timeformat>" + ucFormat.txtTimeFormat.Text + "</timeformat>";
            innerXml += "<culture>" + ucFormat.cboCulture.Text + "</culture>";

            XmlElement root = newXml.CreateElement("format");
            root.InnerXml = innerXml;
            newXml.AppendChild(root);
            newXml.Save(selectingPath);
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            if (lstFiles.Items.Count == 0 || lstFiles.SelectedItems.Count == 0)
                return;

            try
            {
                Process.Start(lstFiles.SelectedItems[0].Tag.ToString());
            }
            catch (Exception exc)
            {
                DBConnection.MyDebugClass.LogThis("Try to open " + lstFiles.SelectedItems[0].Tag.ToString(), exc);
                MessageBox.Show("Please verify that this path existing: " + lstFiles.SelectedItems[0].Tag.ToString());
            }
        }

        private void lstFiles_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstFiles.SelectedItems.Count < 1)
                return;

            string selectingPath = lstFiles.SelectedItems[0].Tag.ToString();
            pnlFormats.Controls.Clear();

            if (!ucBaseFormat.ContainsKey(selectingPath))
            {
                UCBaseFormat newUC = new UCBaseFormat(selectingPath, this);
                ucBaseFormat.Add(selectingPath, newUC);
                pnlFormats.Controls.Add(newUC);
            }
            else
                pnlFormats.Controls.Add((UCBaseFormat)ucBaseFormat[selectingPath]);
        }

        private void FrmBaseFormat_VisibleChanged(object sender, EventArgs e)
        {
            if (this.Visible)
            {
                // Get new (or update) list of source files.
                lstFiles.Items.Clear();
                for (int i = 0; i < _container.frmAddFiles.dgvFiles.Rows.Count; i++)
                {
                    string fileName = _container.frmAddFiles.dgvFiles[1, i].Value.ToString();
                    ListViewItem newItem = new ListViewItem(fileName.Substring(fileName.LastIndexOf("\\") + 1),
                        _container.imgList.Images.IndexOfKey(fileName.Substring(fileName.LastIndexOf("."))));
                    newItem.Tag = fileName;

                    lstFiles.Items.Add(newItem);
                }

                // Update the collection:
                // baseFormat which contains user-defined options to parse a file;
                bool flag = false;
                if (ucBaseFormat.Count > 0)
                {
                    for (int i = 0; i < ucBaseFormat.Count; i++)
                    {
                        flag = false;
                        string fileName = ucBaseFormat.GetKey(i).ToString();
                        int j = 0;

                        while (flag == false && j < lstFiles.Items.Count)
                        {
                            if (lstFiles.Items[j].Tag.ToString() == fileName)
                                flag = true;
                            j++;
                        }

                        if (flag == false)
                        {
                            ucBaseFormat.RemoveAt(i);
                            i--;
                        }
                    }
                }

                txtDatabase.Text = "Database: " + _container.frmConnect.dbc.Database;

                if (lstFiles.Items.Count > 0)
                {
                    lstFiles.Items[0].Selected = true;
                    lstFiles.Focus();
                }
            }
        }
    }
}
